package project.mafia.network;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.LinkedList;

public class Connection extends Thread{
	private Socket socket;
	private ObjectInputStream oistream;
	private ObjectOutputStream oostream;
	private boolean running;
	private LinkedList<Packet> packetQueue;
	public Connection(String ip,int port) throws IOException {
		packetQueue = new LinkedList<Packet>();
		socket = new Socket(ip,port);
		oostream = new ObjectOutputStream(socket.getOutputStream());
		sendPacket(new Packet(0));
		oistream = new ObjectInputStream(socket.getInputStream());
		
	}

	public void run(){
		running = true;
		Packet receive;	
		while(running){
			try {
				receive = (Packet)oistream.readObject();
				switch(receive.getType()){
				case 0: // connect
					break;
				case 1: // disconnect
					close();
					stopConnectionThread();
					// make disconnect message
					break;
				case 2: // user data
					String[] userData = receive.getData();
					for(int i = 0; i < userData.length; i++){
						switch(i){
						case 0:	
							System.out.println("Nick Name : " + userData[i]);
							break;
						case 1:	
							System.out.println("Job : " + userData[i]);
							break;
						case 2:	
							System.out.println("Condition : " + userData[i]);
							break;
						}
					}
					packetQueue.add(receive);
					break;
				case 3:
					packetQueue.add(receive);
					break;
				}

			} catch (ClassNotFoundException | IOException e) {
				e.printStackTrace();
			}
		}
	}
	public void sendPacket(Packet p) throws IOException{
		oostream.writeObject(p);
		oostream.flush();
		System.out.println("packet sent");
	}
	/**
	 * Close socket stuff
	 * @throws IOException
	 */
	public void close() throws IOException{
		oistream.close();
		oostream.close();
		socket.close();
	}
	public void stopConnectionThread(){
		running = false;
	}
	/**
	 * 
	 * @return packet, if There is no packet, return null
	 */
	public synchronized Packet getPacket(){
		if(packetQueue.size()>0){
			Packet p = packetQueue.get(0);
			packetQueue.remove(0);
			return p;
		}
		return null;
	}
}
